﻿
// Stuff for all pages
$(document).ready(function () {
    "use strict";
    
    moment.lang("da");
    
    theCup.convertTimestamps();

    setInterval(theCup.convertTimestamps, 5000);

    $(".comments").emoticonize();

    // Comment Ajax handlers
    $(".comments").on("click", ".ajaxDelete", function (event) {
        var id = $(event.target).data("commentid");

        $.post("/Comment/Delete/", { "id": id }, function (data, textStatus, jqXHR) {
            $("#" + id).slideUp(400, function () {
                $(this).remove();
                alertify.success("kommentar slettet!");
            });
        });
    });

    $("#commentResponse").on("click", ".ajaxPost", function (event) {
        var btn = $(event.target);
        var id = btn.data("id");
        var uuid = btn.data("uuid");
        var type = btn.data("type");
        var area = btn.siblings("textarea");
        var txt = area.val();
        area.val("");

        $.post("/Comment/Create/", { "linkId": id, "linkUuid": uuid, "text": txt, "type": type }, function (data, textStatus, jqXHR) {
            $(".comments").prepend(data);
            theCup.convertTimestamps();
            alertify.success("kommentar tilføjet");
        });
    });

    alertify.set({
        labels: {
            ok: "ja",
            cancel: "nej"
        },
        delay: 5000,
        buttonReverse: true
    });
});

var theCup = (function () {
    "use strict";
    // Geolocation

    /// Pass the id you want to update with geo info
    function getGmapForCurrentLoc(id) {
        if (id === undefined)
            return;

        //console.debug("unused");
        var elem = document.getElementById(id);

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
        }
    }

    function geoSuccess(position) {
        var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=12&size=300x300&sensor=false";
        
        elem.innerHTML = "<img src='" + img_url + "' alt='geogmap'>";
    }

    function geoError() {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                elem.innerHTML = "User denied the request for Geolocation.";
                break;
            case error.POSITION_UNAVAILABLE:
                elem.innerHTML = "Location information is unavailable.";
                break;
            case error.TIMEOUT:
                elem.innerHTML = "The request to get user location timed out.";
                break;
            case error.UNKNOWN_ERROR:
                elem.innerHTML = "An unknown error occurred.";
                break;
            default:
                elem.textContent = "unknown error";
                break;
        }
    }

    /// Get Geo Location for an address
    function getGeoLocForAddress(geoAddress, callback) {
        $.ajax({
            dataType: "json",
            url: "https://maps.googleapis.com/maps/api/geocode/json",
            data: { address: geoAddress },
            success: callback
        });
    }

    /// Create Google Maps img from Location object
    function getGmapForGeoLoc(loc) {
        var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=" + loc.lat + "," + loc.lng + "&zoom=12&size=300x300&sensor=false";
        var img = document.createElement("img");
        img.setAttribute("src", img_url);
        img.setAttribute("alt", "geogmap");
        return img;
    }

    // Misc functions
    function updateScore(form) {
        if (form == null) {
            // fetch default form from _ScoreVert partial view
            form = document.forms["scoreVert"];
        }
        var inStrokes = 0, outStrokes = 0, inPutts = 0, outPutts = 0;

        for (var i = 1; i < 10; i++) {
            outStrokes += form["S" + i].value === "" ? 0 : parseInt(form["S" + i].value);
            outPutts += form["P" + i].value === "" ? 0 : parseInt(form["P" + i].value);
        }

        for (var j = 10; j < 19; j++) {
            inStrokes += form["S" + j].value === "" ? 0 : parseInt(form["S" + j].value);
            inPutts += form["P" + j].value === "" ? 0 : parseInt(form["P" + j].value);
        }

        $("#outStrokes").text(outStrokes);
        $("#inStrokes").text(inStrokes);
        $("#totalStrokes").text(inStrokes + outStrokes);
        $("#netto").text(inStrokes + outStrokes - parseInt(form["PlayingHandicap"].value));

        $("#outPutts").text(outPutts);
        $("#inPutts").text(inPutts);
        $("#totalPutts").text(inPutts + outPutts);
    }

    // Uses Moment's .fromNow()
    function convertTimestamps() {
        $("time").each(function (idx, elem) {
            $(elem).text(moment(elem.getAttribute('datetime')).fromNow());
        });
    }

    function addGolfNews() {
        $.getJSON("/api/golfnews/golfdk", function (data) {
            var items = [];
            $.each(data, function (key, newsitem) {
                items.push("<div class='fademe'><time datetime='" + newsitem.PublishedDate + "'></time> <a href='" + newsitem.Link + "' title='" + newsitem.TextContent + "' target='_blank'>" + newsitem.Title + "</a></div>");
            });

            $("#newsloading").hide();

            $(".newsitems").append(items.join(''));
            convertTimestamps();

            $(".fademe").each(function (index, elem) {
                $(elem).delay(50 * index).fadeIn(1000);
            });
        });
    }
    
    return {
        getGmapForCurrentLoc: getGmapForCurrentLoc,
        getGeoLocForAddress: getGeoLocForAddress,
        getGmapForGeoLoc: getGmapForGeoLoc,
        updateScore: updateScore,
        convertTimestamps: convertTimestamps,
        addGolfNews: addGolfNews
    };
})();

var matchplay = (function(){
    "use strict";

    function enableDropdowns() {
        $('#ResultString').prop('disabled', false);
        $('#Player2Id').prop('disabled', false);
    }

    function disableDropdowns() {
        $('#ResultString').prop('disabled', 'disabled');
        $('#Player2Id').prop('disabled', 'disabled');
    }

    function updatePossibleWinners(playerid) {
        disableDropdowns();

        var thisvalue = $("#Player2Id option:selected").val();
        var thistext = $("#Player2Id option:selected").text();

        $('#ResultString').empty().append('<option value="0|0">A/S</option>').val(0);
        for (var i = 1; i < 11; i++) {
            $('#ResultString').append('<option value="' + playerid + '|' + i + '">Jeg vandt ' + i + 'UP' + '</option>').val(playerid);
        }
        for (var j = 1; j < 11; j++) {
            $('#ResultString').append('<option value="' + thisvalue + '|' + j + '">' + thistext + ' vandt ' + j + 'UP' + '</option>').val(playerid);
        }

        enableDropdowns();
    }

    // obj = HtmlInputElement that was clicked
    // ev = datetimepicker object
    function updateOpponents(obj, ev, playerid) {
        disableDropdowns();

        // extract event date
        var date = ev.date;
        
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: "/api/MatchPlay/",
            data: $.param({ date: date.toJSON(), playerid: playerid }),
            success: function (data) {
                $('#Player2Id').empty(); // Clear the table body.
                $.each(data, function (key, val) {
                    $('#Player2Id').append('<option value="' + val.Id + '">' + val.DisplayName + '</option>').val(val.Id);
                });
                updatePossibleWinners(playerid);
            },
            error: function () {
                alertify.error("failed to fetch players played for season");
            }
        });

        enableDropdowns();
    }
    
    return {
        updateOpponents: updateOpponents,
        updatePossibleWinners: updatePossibleWinners,
        disableDropdowns: disableDropdowns,
        enableDropdowns: enableDropdowns
    };
})();

// deferred loading of webfonts, for faster mobile loads
WebFontConfig = {
    google: { families: ['Coming+Soon::latin'] } // , 'Patrick+Hand::latin', 'Walter+Turncoat::latin', 'Neucha::latin'
};
(function() {
    var wf = document.createElement('script');
    wf.src = ('https:' === document.location.protocol ? 'https' : 'http') +
      '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
})();